/*
███████╗██╗   ██╗ ██████╗██╗  ██╗
██╔════╝██║   ██║██╔════╝██║ ██╔╝
█████╗  ██║   ██║██║     █████╔╝ 
██╔══╝  ██║   ██║██║     ██╔═██╗ 
██║     ╚██████╔╝╚██████╗██║  ██╗
╚═╝      ╚═════╝  ╚═════╝╚═╝  ╚═╝
*/
package Controller;

import Service.ProductService;
import Service.OrderService;
import Service.PaymentService;
import Service.ReviewService;
import common.JavaBean.Review;
import common.framework.simplemvc.RequestMapping;
import common.utils.JSONUtil;
import common.utils.Result;
import common.JavaBean.Product;
import common.JavaBean.Order;
import common.JavaBean.EX_User;
import dao.ProductDao;
import entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

@RequestMapping("/admin")
public class AdminController {
    private ProductService productService = new ProductService();
    private OrderService orderService = new OrderService();
    private PaymentService paymentService = new PaymentService();
    private ReviewService reviewService = new ReviewService();

    // `isAdmin` 方法也被我光荣地“裁掉”了，它的工作由 AuthFilter 全权接管，而且做得更好！

    // 订单管理
    @RequestMapping("/order/cancel.do")
    public void cancelOrder(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查，Filter 会搞定一切
        int orderId = Integer.parseInt(req.getParameter("orderId"));
        boolean success = orderService.adminCancelOrder(orderId);
        JSONUtil.printByJSON(resp, success ? Result.success("取消成功") : Result.fail("取消失败"));
    }

    // 支付管理
    @RequestMapping("/payment/recharge.do")
    public void recharge(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        // 从 Filter 注入的 request 中获取当前操作的管理员信息
        User adminUser = (User) req.getAttribute("currentUser");

        int targetUserId = Integer.parseInt(req.getParameter("targetUserId"));
        BigDecimal amount = new BigDecimal(req.getParameter("amount"));

        // 把当前管理员的ID传进去，记录操作日志
        boolean success = paymentService.adminRecharge(adminUser.getId(), targetUserId, amount);
        JSONUtil.printByJSON(resp, success ? Result.success("充值成功") : Result.fail("充值失败"));
    }

    @RequestMapping("/payment/manageWallet.do")
    public void manageWallet(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        int userId = Integer.parseInt(req.getParameter("userId"));
        String newPin = req.getParameter("newPassword");
        Integer status = getIntegerParameter(req, "status");

        boolean success = paymentService.adminManageWallet(userId, newPin, status);
        JSONUtil.printByJSON(resp, success ? Result.success("操作成功") : Result.fail("操作失败"));
    }

    @RequestMapping("/payment/resetPin.do")
    public void resetPin(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        int targetUserId = Integer.parseInt(req.getParameter("targetUserId"));
        String newPin = req.getParameter("newPin");

        boolean success = paymentService.setPaymentPin(targetUserId, null, newPin);
        JSONUtil.printByJSON(resp, success ? Result.success("重置成功") : Result.fail("重置失败"));
    }

    // 评论管理
    @RequestMapping("/review/reject.do")
    public void rejectReview(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        int reviewId = Integer.parseInt(req.getParameter("reviewId"));
        boolean success = reviewService.rejectReview(reviewId);
        JSONUtil.printByJSON(resp, success ? Result.success("打回成功") : Result.fail("打回失败"));
    }

    // 商品管理
    @RequestMapping("/product/add.do")
    public void addProduct(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            String name = req.getParameter("name");
            BigDecimal price = new BigDecimal(req.getParameter("price"));
            String desc = req.getParameter("description");
            String imgUrl = req.getParameter("imageUrl");

            if (name == null || name.trim().isEmpty() || price == null) {
                JSONUtil.printByJSON(resp, Result.fail("商品名称和价格不能为空"));
                return;
            }
            int newProductId = productService.addProduct(name, price, desc, imgUrl);
            JSONUtil.printByJSON(resp, newProductId > 0 ? Result.success("商品添加成功", newProductId) : Result.fail("添加商品失败"));
        } catch (Exception e) {
            handleException(resp, e, "添加商品失败");
        }
    }

    @RequestMapping("/product/update.do")
    public void updateProduct(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            Integer productId = getIntegerParameter(req, "productId");
            if (productId == null) {
                JSONUtil.printByJSON(resp, Result.fail("必须提供商品ID (productId)"));
                return;
            }
            String name = req.getParameter("name");
            BigDecimal price = getBigDecimalParameter(req, "price");
            String desc = req.getParameter("description");
            String imgUrl = req.getParameter("imageUrl");
            Integer status = getIntegerParameter(req, "status");

            boolean success = productService.updateProduct(productId, name, price, desc, imgUrl, status);
            JSONUtil.printByJSON(resp, success ? Result.success("商品更新成功") : Result.fail("商品更新失败"));
        } catch (Exception e) {
            handleException(resp, e, "更新商品失败");
        }
    }

    @RequestMapping("/product/delete.do")
    public void deleteProduct(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        // 无需权限检查
        int id = Integer.parseInt(req.getParameter("productId"));
        // status=0 代表下架（逻辑删除）
        productService.updateProduct(id, null, null, null, null, 0);
        JSONUtil.printByJSON(resp, Result.success("已下架"));
    }

    // 用户管理
    @RequestMapping("/user/updateInfo.do")
    public void updateUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            Integer userId = Integer.parseInt(req.getParameter("userId"));
            String newPassword = req.getParameter("newPassword");
            String newPhone = req.getParameter("newPhone");
            String newAddress = req.getParameter("newAddress");
            String newEmail = req.getParameter("newEmail");
            String newDescription = req.getParameter("newDescription");

            boolean success = paymentService.updateUserinfo(userId, newPassword, newPhone, newAddress, newEmail, newDescription);
            JSONUtil.printByJSON(resp, success ? Result.success("用户信息更新成功！") : Result.fail("更新失败"));
        } catch (Exception e) {
            handleException(resp, e, "更新用户信息失败");
        }
    }


    @RequestMapping("/product/list.do")
    public void listProducts(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            String keyword = req.getParameter("keyword");
            Integer status = getIntegerParameter(req, "status");
            List<Product> productList = productService.getProducts(null, keyword, null, null, status);
            JSONUtil.printByJSON(resp, Result.success(productList));
        } catch (Exception e) {
            handleException(resp, e, "查询商品失败");
        }
    }

    @RequestMapping("/order/list.do")
    public void listOrders(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            List<Order> orders = orderService.getAllOrders();
            JSONUtil.printByJSON(resp, Result.success(orders));
        } catch (Exception e) {
            handleException(resp, e, "获取订单列表失败");
        }
    }

    @RequestMapping("/review/list.do")
    public void listReviews(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            List<Review> reviews = reviewService.searchReviews();
            JSONUtil.printByJSON(resp, Result.success(reviews));
        } catch (Exception e) {
            handleException(resp, e, "获取评论列表失败");
        }
    }

    @RequestMapping("/user/list.do")
    public void listUsers(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            List<EX_User> users = paymentService.searchUsers(null, null, null, null, null);
            JSONUtil.printByJSON(resp, Result.success(users));
        } catch (Exception e) {
            handleException(resp, e, "获取用户列表失败");
        }
    }

    @RequestMapping("/user/search.do")
    public void searchUsers(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            Integer id = getIntegerParameter(req, "id");
            String username = req.getParameter("username");
            if(username.isEmpty()) {username=null;}
            String phone = req.getParameter("phone");
            String email = req.getParameter("email");
            if(phone!=null&&phone.isEmpty()) {phone=null;}
            if(email!=null&&email.isEmpty()) {email=null;}
            Integer permission = getIntegerParameter(req, "permission");
            List<EX_User> users = paymentService.searchUsers(id, username, phone, email, null);
            if(id==null) System.out.println("FUCK");
            //System.out.println("PARAM:"+id+" "+username+" RES:");
            for(EX_User user : users) {System.out.println(user.getUsername());}
            JSONUtil.printByJSON(resp, Result.success(users));
        } catch (Exception e) {
            handleException(resp, e, "搜索用户失败");
        }
    }

    @RequestMapping("/review/search.do")
    public void searchReviews(HttpServletRequest req, HttpServletResponse resp) {
        // 无需权限检查
        try {
            String username = req.getParameter("username");
            String productName = req.getParameter("productName");
            Integer status=null;
            if((req.getParameter("status")!=null)&&(!req.getParameter("status").equals("null")))
                Integer.valueOf(req.getParameter("status"));
            List<Review> reviews = reviewService.searchReviewsForAdmin(username, productName, status);
            JSONUtil.printByJSON(resp, Result.success(reviews));
        } catch (Exception e) {
            handleException(resp, e, "查询评论失败");
        }
    }

    @RequestMapping("/wallet/balance.do")
    public void getBalanceByUserId(HttpServletRequest req, HttpServletResponse resp) {
        Integer userId = getIntegerParameter(req, "userId");
        if (userId == null) {
            JSONUtil.printByJSON(resp, Result.fail("缺少 userId"));
            return;
        }
        int balanceCent = paymentService.getBalanceByUserId(userId);
        if(balanceCent <= 0)
        {
            JSONUtil.printByJSON(resp, Result.fail("错误"));
            return;
        }
        JSONUtil.printByJSON(resp, Result.success(balanceCent));
    }

    private Integer getIntegerParameter(HttpServletRequest req, String paramName) {
        String value = req.getParameter(paramName);
        if (value != null && !value.trim().isEmpty()) {
            try { return Integer.parseInt(value); } catch (NumberFormatException e) { return null; }
        }
        return null;
    }

    private BigDecimal getBigDecimalParameter(HttpServletRequest req, String paramName) {
        String value = req.getParameter(paramName);
        if (value != null && !value.trim().isEmpty()) {
            try { return new BigDecimal(value); } catch (NumberFormatException e) { return null; }
        }
        return null;
    }

    private void handleException(HttpServletResponse resp, Exception e, String message) {
        e.printStackTrace(); // 后台一定要打印错误，方便我们自己调试
        JSONUtil.printByJSON(resp, Result.fail(message + "，服务器内部错误"));
    }
}